import React, { ReactNode } from 'react'
import { Select } from 'antd'
import { udConfigProvider } from '@/lib'
import { SelectProps } from 'antd/lib/select'
import _ from 'lodash'

const { Option } = Select

function UdSelect(props: IUdSelectProps) {
  const { options, mapping, ...rest } = props
  const pageContainer = udConfigProvider.ui.getPageContainer() as HTMLElement

  let nodes = []
  if (_.isArray(options) && options.length > 0) {
    let func = ((value: any, index: number, array: any[]) => {
      return <Option key={value.value} value={value.value}>{value.title}</Option> as ReactNode
    })
    if (_.isFunction(mapping)) {
      func = mapping
    } else if (_.isObject(mapping)) {
      func = ((value: any, index: number, array: any[]) => {
        return <Option key={value[(mapping as any).value]} value={value[(mapping as any).value]}>{value[(mapping as any).title]}</Option> as ReactNode
      })
    }
    options.forEach((value, index, array) => {
      nodes.push(func(value, index, array))
    })
  }

  return (
    <Select getPopupContainer={() => pageContainer} optionFilterProp='children' {...rest}>
      {nodes}
    </Select>
  )
}

const UdSelectRef = React.forwardRef((props:any, ref) => {
    return <UdSelect {...props}/>
});

export default React.memo(UdSelectRef)

interface IUdSelectProps extends SelectProps {
  options: {value: string, title: string}[]
  mapping?: ((value: any, index: number, array: any[]) => ReactNode) | { title: string, value: string }
}